package cc.vv.baselibrary.util;


import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;

import cc.vv.baselibrary.bean.PublicViewHolder;
import cc.vv.baselibrary.util.router.RouterConfig;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * 项目内部模块定点路由配置
 *
 * @author: NPF
 * @date: 2018/3/13.
 */
public class BaseResourceUtil {

    private static BaseResourceUtil mInstance;

    private BaseResourceUtil() {

    }

    public static BaseResourceUtil getInstance() {
        if (null == mInstance) {
            synchronized (RouterConfig.class) {
                if (null == mInstance) {
                    mInstance = new BaseResourceUtil();
                }
            }
        }
        return mInstance;
    }

    /** 初始化View资源持有对象*/
    @NonNull
    public void initViewHolderResource(@NonNull FragmentActivity activity, PublicViewHolder viewHolder,@NonNull final ViewEventInterface viewEventInterface){
        if (null == viewHolder) {
            return;
        }
        try {
            Field[] fields = viewHolder.getClass().getDeclaredFields();
            if (null != fields && fields.length > 0) {
                for (int i = 0; i < fields.length; i++) {
                    try {
                        Field field = fields[i];
                        field.setAccessible(true);
                        final int res = getFieldValue("id", field.getName(), activity);
                        if (res != -1) {
                            /* 实例化控件*/
                            field.set(viewHolder, activity.findViewById(res));
                            /* 判断是否需要注册点击事件*/
                            String modifierStr = Modifier.toString(field.getModifiers());
                            if(!modifierStr.equals("private")){
                                ((View) field.get(viewHolder)).setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                            viewEventInterface.viewOnClick(res);
                                    }
                                });
                            }
                        }
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }

    /** 初始化View资源持有对象*/
    @NonNull
    public void initViewHolderResource(@NonNull FragmentActivity activity,@NonNull View view, PublicViewHolder viewHolder,@NonNull final ViewEventInterface viewEventInterface){
        if (null == viewHolder) {
            return;
        }
        try {
            Field[] fields = viewHolder.getClass().getDeclaredFields();
            if (null != fields && fields.length > 0) {
                for (int i = 0; i < fields.length; i++) {
                    try {
                        Field field = fields[i];
                        field.setAccessible(true);
                        final int res = getFieldValue("id", field.getName(), activity);
                        if (res != -1) {
                            /* 实例化控件*/
                            field.set(viewHolder, view.findViewById(res));
                            /* 判断是否需要注册点击事件*/
                            String modifierStr = Modifier.toString(field.getModifiers());
                            if(!modifierStr.equals("private")){
                                ((View) field.get(viewHolder)).setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        viewEventInterface.viewOnClick(res);
                                    }
                                });
                            }
                        }
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断ResourceID相同
     */
    public static boolean whetherResourceIDSame(int resIdOne, int resIdTwo) {
        return resIdOne == resIdTwo;
    }

    /**
     * 根据给定的类型名和字段名，返回R文件中的字段的值
     *
     * @param typeName  属于哪个类别的属性 （id,layout,drawable,string,color,attr......）
     * @param fieldName 字段名
     * @return 字段的值
     * @throws Exception
     */
    public int getFieldValue(String typeName, String fieldName, Context context) {
        int i = -1;
        try {
            Class<?> clazz = Class.forName(context.getPackageName() + ".R$" + typeName);
            i = clazz.getField(fieldName).getInt(null);
        } catch (Exception e) {
            Log.d("" + context.getClass(), "没有找到" + context.getPackageName() + ".R$" + typeName + "类型资源 " + fieldName + "请copy相应文件到对应的目录.");
            return -1;
        }
        return i;
    }

    public interface ViewEventInterface{
        void viewOnClick(int resId);
    }
}
